var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
let session = require('express-session');   // 使用session模块

var index = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
var blog = require('./routes/blog');
var ueditor = require('./util/ueditor/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  /*
   secret 是必需的选项，这是用于签名会话ID cookie的密钥。
   这可以是单个密钥的字符串或多个秘密的数组。
   如果提供了一组密钥，只有第一个元素将用于签名会话ID cookie，而在验证请求中的签名时，将考虑所有元素。
   */
  secret: 'secret',
  // 这里的name值得是cookie的name，默认cookie的name是：connect.sid
  name: 'sid',
  'resave': false,
  saveUninitialized: true,
  cookie: {
    maxAge: 30 * 60 * 1000
  }
}))

app.use(function (req, res, next) {
  var views = req.session.views
  if (!views) {
    views = req.session.views = {}
  }
  // get the url pathname
  var pathname = req.url;
  // count the views
  views[pathname] = (views[pathname] || 0) + 1;
  next();
})

app.use('/', index);
app.use('/users', users);
app.use('/api', api);
app.use('/blog', blog);
app.use('/ueditor', ueditor);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
